package com.shady.diskmanger.utils;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileMd5Utils {
    /**
     * 计算文件的md5码
     * @param file
     * @return
     * @throws Exception
     */
    public static String md5OfFile(File file) {
        MessageDigest md;
        FileInputStream fs;
        try {
            md = MessageDigest.getInstance("MD5");
            fs = new FileInputStream(file);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        BufferedInputStream bs = new BufferedInputStream(fs);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while (true) {
            try {
                if (!((bytesRead = bs.read(buffer, 0, buffer.length)) != -1)) break;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            md.update(buffer, 0, bytesRead);
        }
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte bite : digest) {
            sb.append(String.format("%02x", bite & 0xff));
        }
        try {
            fs.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }
}
